/**
* 版权声明：厦门睿商网络科技有限公司 版权所有 违者必究
* 日    期：2021-01-08
*/
package com.rzico.account.service;

import com.alibaba.fastjson.JSON;
import com.rzico.account.entity.Payment;
import com.rzico.account.entity.PhonePayment;
import com.rzico.account.mapper.PhonePaymentMapper;
import com.rzico.account.model.Attach;
import com.rzico.base.BaseMapper;
import com.rzico.base.impl.BaseServiceImpl;
import com.rzico.basics.entity.Member;
import com.rzico.basics.service.MemberService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.core.MessageBuilder;
import org.springframework.amqp.core.MessageProperties;
import org.springframework.amqp.rabbit.connection.CorrelationData;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.*;

/**
 * <pre>
 * 豆讯话费支付业务类
 * </pre>
 *
 * @author Rzico Boot
 * @version 1.0
 */
@Service
public class PhonePaymentService extends BaseServiceImpl<PhonePayment, String> {

    protected Logger logger = LoggerFactory.getLogger(this.getClass());

    @Autowired
    private PhonePaymentMapper phonePaymentMapper;

    @Override
    public BaseMapper<PhonePayment, String> getMapper() {
        return phonePaymentMapper;
    }

    @Autowired
    private RabbitTemplate rabbitTemplate;

    @Autowired @Lazy
    private MemberService memberService;

    /**
     * 通过支付单号查找支付记录
     * @param sn
     * @return
     */
    public PhonePayment findBySn(String sn){
        Map<String,Object> params = new HashMap<>();
        params.put("sn",sn);
        List<PhonePayment> payments = super.selectList(params);
        if (payments.size()>0) {
            return payments.get(0);
        } else {
            return null;
        }
    }

    /**
     * 更新订单支付成功记录
     * @param sn
     * @param tranSn
     * @throws Exception
     */
    public void handle(String sn,String tranSn) throws Exception {
        PhonePayment phonePayment = findBySn(sn);
        if (!phonePayment.getStatus().equals(Payment.STATUS_SUCCESS)) {

            if (phonePayment.getPaymentPluginId().equals("weixinPayPlugin") ||
                    phonePayment.getPaymentPluginId().equals("weixinMiniPayPlugin")
            ) {
                phonePayment.setFee(phonePayment.getAmount().multiply(new BigDecimal(0.006)).setScale(2,BigDecimal.ROUND_HALF_DOWN));
            }

            phonePayment.setStatus(Payment.STATUS_SUCCESS);
            phonePayment.setTranSn(tranSn);
            phonePaymentMapper.updateByPrimaryKeySelective(phonePayment);

            //通过MQ异步通知支付成功
            if (phonePayment.getAttach()!=null) {
                Attach attachQueue = phonePayment.decodeAttach();
                attachQueue.setCode("0000");

                if (phonePayment.getType().equals(Payment.TYPE_VIP)) {
                    Member member = memberService.selectByPrimaryKey(phonePayment.getMemberId());
                    Date d = new Date();
                    if (member.getVipExpired()!=null && member.getVipExpired().after(d)) {
                        d = member.getVipExpired();
                    }
                    Integer vipType = Integer.parseInt(attachQueue.getId());
                    if (vipType==0) {
                        d = org.apache.commons.lang3.time.DateUtils.addMonths(d, 1);
                    } else
                    if (vipType==1) {
                        d = org.apache.commons.lang3.time.DateUtils.addYears(d, 1);
                    } else {
                        d = org.apache.commons.lang3.time.DateUtils.addYears(d, 99);
                    }
                    d = org.apache.commons.lang3.time.DateUtils.truncate(d, Calendar.DATE);
                    member.setVipExpired(d);
                    memberService.updateByPrimaryKeySelective(member);
                } else {
                    Message message = MessageBuilder
                            .withBody(JSON.toJSONString(attachQueue).getBytes())
                            .setContentType(MessageProperties.CONTENT_TYPE_JSON)
                            .build();
                    CorrelationData correlationData = new CorrelationData();
                    correlationData.setId(UUID.randomUUID().toString());
                    logger.info("发送 MQ");
                    rabbitTemplate.convertAndSend("directExchange", attachQueue.getQueue() + ".key", message, correlationData);
                }
            }

        }
    }


}
